import axios from "axios";
import { Message } from "element-ui";
import router from "@/router";
import { has, pick } from "lodash";


// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  withCredentials: true,
  timeout: 600000
});

// request interceptor
service.interceptors.request.use(
  config => {
    return config;
  },
  error => {
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.code !== 200) {
      if (res.code !== 401) {
        Message({
          message: res.message || "Error",
          type: "error",
          duration: 5 * 1000
        });
      }
      if (res.code === 401) {
        router.push({ path: "/login" });
        return res;
      }
      return {
        result: false,
        ...res
      };
    } else {
      return {
        result: true,
        ...res
      };
    }
  },
  error => {
    console.log("err" + error); // for debug
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
);

const request = ({ url, data, method }) => {
  return service({
    url,
    method: method || "post",
    data,
    transformRequest: [
      function(data, headers) {
        headers.post = { "content-type": "application/json" };
        if (has(data, "paramObject")) {
          const { paramObject } = data;
          const keyArr = Object.keys(paramObject).filter(
            key => paramObject[key] !== ""
          );
          const params = {
            ...data,
            paramObject: pick(paramObject, keyArr)
          };
          return JSON.stringify(params);
        } else {
          return JSON.stringify(data);
        }
      }
    ]
  });
};

const upload = ({ url, data, method }) => {
  return service({
    url,
    method: method || "post",
    data
  });
};

export { request, upload };
